import type { UserInfo, DeptsInfo } from '/#/store';
import type { ErrorMessageMode } from '/#/axios';
import { toRaw } from 'vue';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/enums/roleEnum';
import { PageEnum } from '/@/enums/pageEnum';
import { ROLES_KEY, TOKEN_KEY, USER_INFO_KEY, DEPTS_KEY } from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { GetUserInfoModel, LoginParams } from '/@/api/sys/model/userModel';
import {
  loginApi,
  getUserInfo,
  logout,
  queryUser,
  sendCodeApi,
  updatePasswordApi,
  deptGetApi,
} from '/@/api/user/login';
import { isArray } from '/@/utils/is';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { usePermissionStore } from '/@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { messageFn, resetPinia } from '../utils';
import { h } from 'vue';
import { assign } from 'lodash-es';
import { useRouter } from 'vue-router';

const getAuthList = (
  { source = [], type = RoleEnum.MENU }: { source: any[]; type: RoleEnum },
  res: string[] = [],
) => {
  for (const el of source) {
    if (el.type === type) {
      res.push(el.permission);
    }
    if (el.children && el.children.length) {
      getAuthList({ source: el.children, type }, res);
    }
  }
  return res;
};

interface UserState {
  userInfo: Nullable<UserInfo>;
  token?: string;
  roleList: string[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  depts: DeptsInfo[];
  id?: string | number;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: null,
    // token
    token: undefined,
    // roleList
    roleList: [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
    // 部门信息
    depts: [],
    // 用户手机ID
    id: undefined,
  }),
  getters: {
    getUserInfo(): UserInfo {
      return this.userInfo || getAuthCache<UserInfo>(USER_INFO_KEY) || {};
    },
    getToken(): string {
      return this.token || getAuthCache<string>(TOKEN_KEY);
    },
    getBtnAuthList(): string[] {
      return this.roleList.length > 0 ? this.roleList : getAuthCache<string[]>(ROLES_KEY);
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
    getPageNameRoles(): string[] {
      // 获取页面权限
      const { permissions } = toRaw(this.getUserInfo);

      const res = getAuthList({
        source: permissions as [],
        type: RoleEnum.MENU,
      });

      return res;
    },
    getBtnNameRoles(): string[] {
      // 获取按钮权限
      const { permissions } = toRaw(this.getUserInfo);
      const res = getAuthList({
        source: permissions as [],
        type: RoleEnum.BUTTON,
      });
      return res;
    },
    getCustomPermissions(): Recordable[] {
      // 获取自定义菜单栏
      const { custom_permissions = [] } = toRaw(this.getUserInfo);

      // const res = custom_permissions.map((p) => p.permission);
      return custom_permissions;
    },
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''; // for null or undefined value
      setAuthCache(TOKEN_KEY, info);
    },
    setDepts(depts: DeptsInfo[]) {
      this.depts = depts;
      setAuthCache(DEPTS_KEY, depts);
    },
    setBtnAuthList(roleList: string[]) {
      this.roleList = roleList;
      setAuthCache(ROLES_KEY, roleList);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    resetState() {
      this.userInfo = null;
      this.token = '';
      this.roleList = [];
      this.sessionTimeout = false;
    },
    async noLogin() {
      const { currentRoute } = useRouter();
      const { token } = currentRoute.value.query || {};
      const currentUrl = window.location.href;
      const tokenIndex = currentUrl.indexOf('token=');
      let urlToken = '';
      if (tokenIndex !== -1) {
        urlToken = currentUrl.slice(tokenIndex + 6);
      }
      const newToken = token || urlToken;
      if (!newToken) return null;

      this.setToken(newToken as string);
      const depts = await deptGetApi();

      this.setDepts(depts);
      const res = await this.getUserInfoAction();
      return res;
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
        mode?: ErrorMessageMode;
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        // 清除token
        this.setToken('');
        const { goHome = true, ...loginParams } = params;
        const data = await loginApi(loginParams);
        if (data.code !== 0) {
          console.log(data.msg, '-----登录错误');
          return Promise.reject(data.msg);
        }
        const result = data.data;
        const { access_token, depts } = result;
        resetPinia();
        // save token
        this.setToken(access_token);
        this.setDepts(depts);
        return this.afterLoginAction(goHome);
      } catch (error) {
        console.log(error, '-----登录接口错误');
        return Promise.reject(error);
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
      if (!this.getToken) return null;
      // get user info
      const userInfo = await this.getUserInfoAction();

      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        if (!permissionStore.isDynamicAddedRoute) {
          const routes = await permissionStore.buildRoutesAction();

          routes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);
        }
        goHome && (await router.replace(userInfo?.homePath || PageEnum.BASE_HOME));
      }
      return userInfo;
    },
    async getUserInfoAction(): Promise<UserInfo | null> {
      if (!this.getToken) return null;
      const userInfo = await getUserInfo();
      this.setUserInfo({
        permissions: userInfo.data?.permissions,
      });
      
      const { user } = userInfo.data;
      const btnAuths = this.getBtnNameRoles;

      if (isArray(btnAuths)) {
        this.setBtnAuthList(btnAuths);
      } else {
        userInfo.btnAuths = [];
        this.setBtnAuthList([]);
      }
      const info = {
        userId: user.id,
        username: user.nickname,
        realName: user.nickname,
        avatar: user.avatar,
        btnAuths: btnAuths,
        address: {
          address: userInfo.data?.address,
          province: userInfo.data?.province,
          city: userInfo.data?.city,
          area: userInfo.data?.area,
          street: userInfo.data?.street,
        },
        permissions: userInfo.data?.permissions,
        roles: userInfo.data?.roles,
        custom_permissions: userInfo.data?.custom_permissions,
      };
      this.setUserInfo(info);
      return info;
    },
    /**
     * @description: 查询手机用户
     */
    async sendCode(params: object) {
      const { code, data, msg } = await queryUser(params);
      if (code === 0) {
        this.id = data.id;
        const reslut = this.sendHandler({ id: data.id, scene: 3 });
        return reslut;
      } else {
        messageFn('error', msg);
        return false;
      }
    },

    /**
     * @description: 发送短信验证码
     */
    async sendHandler(formData: object) {
      const { code, msg } = await sendCodeApi(formData);
      if (code === 0) {
        messageFn('success', '短信已发送，请注意查收！');
        return true;
      } else {
        messageFn('error', msg);
        return false;
      }
    },

    /**
     * @description: 修改密码
     */
    async editPassword(formData: object) {
      formData = assign(formData, { id: this.id });
      const { code, msg } = await updatePasswordApi(formData);
      if (code === 0) {
        messageFn('success', '密码修改成功！');
        return true;
      } else {
        messageFn('error', msg);
        return false;
      }
    },

    /**
     * @description: logout
     */
    async logout(goLogin = false) {
      if (this.getToken) {
        try {
          await logout();
        } catch {
          console.log('注销Token失败');
        }
      }
      this.setToken(undefined);
      this.setSessionTimeout(false);
      this.setUserInfo(null);
      this.setDepts([]);
      // goLogin && router.push(PageEnum.BASE_LOGIN);
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
        onOk: async () => {
          await this.logout(true);
        },
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
